package com.xincheng.shuimalong.api;

import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.widget.Toast;

import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.dialog.CustomProgressDialog;
import com.xincheng.shuimalong.entity.BaseEntity;

import java.util.HashMap;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * Created by xuhao on 2017/6/12.
 */

public abstract class BaseObserver<T> implements Observer<BaseEntity> {
    private Context mContext;
    private CustomProgressDialog progressDialog;
    private Disposable mDisposable;


    protected BaseObserver(Context context) {
        this.mContext = context.getApplicationContext();
    }

    protected BaseObserver(Context context, String dialogMessage) {
        this.mContext = context.getApplicationContext();
        initProgressDialog(context,dialogMessage);
    }

    public void initProgressDialog(Context context,String dialogMessage) {
        if (progressDialog == null) {
            progressDialog = CustomProgressDialog.createDialog(context);
        }
        progressDialog.setMessage(dialogMessage);
        progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                if(mDisposable != null) {
                    mDisposable.dispose();
                }
            }
        });
    }
    public void onStart() {
        if(progressDialog != null && !progressDialog.isShowing()) {
            progressDialog.show();
        }
    }


    @Override
    public void onSubscribe(Disposable d) {
        XLog.e("value==>" + d.toString());
        this.mDisposable = d;
    }

    @Override
    public void onNext(BaseEntity value) {
        XLog.e("value==>" + value.toString());
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (value != null && value.isSuccess()) {
            onHandleSuccess(value.getData(), value.getMessage());
        } else {
            onHandleError(value.getMessage());
        }
    }

    @Override
    public void onError(Throwable e) {
        XLog.e(e.getMessage());
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        onHandleError("数据异常");
    }

    @Override
    public void onComplete() {
        XLog.e("onComplete");
    }


    protected abstract void onHandleSuccess(Object data, String msg);

    protected void onHandleError(String msg) {
        CommonUtil.showToast(mContext, msg);
    }
}
